/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { getRichTextContent } from '@src/api/SystemApi';
import { getAsyncTaskListInitData } from '@src/api/InitDataApi'
/* util */
import { isCalendar } from '@src/util/CalendarUtil';
import { getRootWindow } from '@src/util/dom';
import { t } from '@src/locales'
import { isBasicEditionHideEvent, isBasicEditionHidePart, isBasicEditionHidePay, isBasicEditionHidePrintTask, isBasicEditionHideProduct, isBasicEditionHideServe } from '@shb-lib/version';
import { getAllGrayInfo } from '@src/util/grayInfo';
import { formatDate } from 'pub-bbx-utils';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { safeNewDate } from '@src/util/time';
import { atTextToHtml1 } from '@src/util/atText'
import { storageGet, storageSet } from '@src/util/storage';
import { ctiCallOut } from '@src/util/ctisdk';
/* enum */
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
import StorageKeyEnum from '@model/enum/StorageKeyEnum' 
import { LogisticsFieldNameMappingEnum } from '@model/enum/FieldMappingEnum'
import TaskStateEnum from '@model/enum/TaskStateEnum.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { GrayFunctionEnum } from '@model/grayFunction';
import { TaskExceptionStateLabelEnum, TaskCreateMethodLabelEnum } from '@model/enum/LabelEnum.ts';
/* model */
import { fields, allExport, AbnormalList, qualityFields, FaultLibrary } from '@src/modules/task/list/TaskFieldModel.js'; 
/* service */
import { filterExportFieldWithFormType } from '@service/FieldService.ts';
import { smoothLogisticsField } from '@service/LogisticsService'
/* export */
import { taskListExport } from '@src/api/Export';
/* components */ 
import ArchiveDialog from '@src/component/compomentV2/ArchiveDialog';
/* mixins */ 
import LogisticsMixin from '@src/mixins/logisticsMixin'
import AuthMixin from '@src/mixins/authMixin';
import { formatAddress } from 'pub-bbx-utils';
// 列表筛选字段类型
const LIST_FILTER_FORM_TYPE = ['attachment', 'autograph'];

export default {
  name: 'customer-task-table',
  mixins: [LogisticsMixin, AuthMixin],
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
    auth: {
      type: Object,
      default: () => ({})
    },
    extraAttrs: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isOpenData,
      exportStorageKey: StorageKeyEnum.TaskListExport,
      initData: {},
      isCalendar,
      taskList: [],
      columns: [],
      exportColumns: [],
      taskFields: [],
      taskReceiptFields: [],
      taskCommonFields: [],
      partField: '', // 选备件导出的自定义字段
      planTimeType: '', // 判断计划时间展示的样式
      planStartTimeType: '', // 判断计划开始时间展示的样式
      planEndTimeType: '', // 判断计划完成时间展示的样式
      allGrayInfo: null,
      taskListExport,
      loading: false,
      searchModel: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
      },
      sortModel: null, // 排序
      taskStateEnum: TaskStateEnum,
      taskStatusFields: [
        'onceOverTime',
        'onceRefused',
        'oncePaused',
        'onceRollback',
        'onceReallot',
        'oncePrinted',
        'positionException',
        'source'
      ],
      richtextVisible: false,
      richtextContent: null,
    }
  },
  computed: {
    customerId() {
      return this.shareData.customer ? this.shareData.customer.id : '';
    },
    customerName() {
      return this.shareData.customer ? this.shareData.customer.name : '';
    },
    /** 导出工单权限 */
    exportTaskPermission() {
      return this.auth?.TASK_EXPORT
    },
    /** 查看工单全部权限 */
    permissionTaskView() {
      return this.globalIsHaveUserViewDetailAuth
    },
    /** 工单列表字段 */
    taskListFields() {
      let fixedFields = fields.slice();

      return []
        .concat(fixedFields)
        .filter((f) => f.formType !== 'separator' && f.formType !== 'info')
        .filter(item=>{
          if(item.fieldName == 'planTime') {
            return !this.isCalendar
          } else if(item.fieldName == 'planStartTime' || item.fieldName == 'planEndTime'){
            return this.isCalendar
          }
          return true 
        })
        .sort((a, b) => a.orderId - b.orderId);
    },
    /** 工单类型过滤后的字段 */
    taskTypeFilterFields() {
      let fields = this.taskFields.concat(this.taskReceiptFields) || [];
      let taskTypeFilterFields = fields.filter((field) => {
        return (
          LIST_FILTER_FORM_TYPE.indexOf(field.formType) == -1
          && field.isSystem == 0
        )
      });
      return taskTypeFilterFields;
    },
    /** 公共字段 */
    commonFields(){
      return this.taskCommonFields.filter(item=>item.isCommon)
    },
    // 基础版功能是否隐藏打印
    isBasicEditionHidePrintTask() {
      return isBasicEditionHidePrintTask() 
    },
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct() 
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    // 基础版功能是否隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent() 
    },
    // 基础版功能是否隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart() 
    },
    // 基础版功能是否隐藏服务项目
    isBasicEditionHideServe() {
      return isBasicEditionHideServe() 
    },
    // 是否开启结算规则灰度
    isSettlementRuleGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.settlementRule
    },
    /** 
    * @description 是否开启服务商灰度
    */
    isProviderManager() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.providerManager || false
    },
    /** 
    * @description 是否开启云仓灰度
    */
    isCloudwarehouse() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskCloudWarehouse || false
    },
    /**
     * @des 海伦哲灰度判断
     */
    isHandlerGray(){
      return this.allGrayInfo && this.allGrayInfo[GrayFunctionEnum.HANDLERGRAY]
    },
    /** 
    * @description 是否开启故障库灰度
    */
    isFaultGrayscale(){
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.faultLibrary
    },
    hasCallAuth() {
      return !!getRootWindow(window).CTI
    },
    /** 判断呼叫中心开启电话 */
    callCenterModule() {
      return localStorage.getItem('call_center_module') && Number(localStorage.getItem('call_center_module'))
    },
  },
  filters: {
    displaySelect(value) {
      if (!value) return null;
      if (value && typeof value === 'string') {
        return value;
      }
      if (Array.isArray(value) && value.length) {
        return value.join('，');
      }
      return null;
    },
    /** 审批状态 */
    displayApprove(value) {
      return value == 0 ? t('common.task.approveStatus.noApprove') : t('common.task.approveStatus.approve')
    },
    qualityStatus(value){
      if(!value) return ''
      return value == 'IN' ? t('common.task.qualityGuarantee.in') : t('common.task.qualityGuarantee.out')
    }
  },
  mounted() {
    this.getTurnOnTaskExceptionNodeInfo()
    // 获取是否自定义导出字段 目前只有博立有数据 其它的数据为空
    this.getExpensePartField()
    // 页面初始化
    this.initialize()
    this.getSystemGrayInfo()
  },
  methods: {
    // 查看归档工单
    checkArchive(){
      if(this.shareData.isArchiveView) this.$refs.ArchiveDialog.open({customerId:this.customerId});
      else{
        this.$confirm(t('customer.detail.customerTaskTable.checkArchiveConfirm.message'), t('customer.detail.customerTaskTable.checkArchiveConfirm.title'), {
          type: 'warning'
        }).then(()=>{}).catch(()=>{})
      }
    },
    /**
     * @description 排序变化
     * @param {Object} option 配置
     */
    sortChange(option) {
      const UserNameConvertMap = {
        'createUserName': 'createUser',
        'executorName': 'executorUser',
        'customer': 'customerName',
        'qualityStartTime': 'qualityStartTime',
        'qualityEndTime': 'qualityEndTime'
      }

      try {
        let {
          prop,
          order
        } = option;

        if (!order) {
          this.sortModel = null;
          return this.fetchData();
        }
        const sortedField = this.taskListFields.filter((sf) => sf.fieldName === prop)[0] || {};

        let isSystem = 0;
        let isConvertedProp = Object.keys(UserNameConvertMap).indexOf(prop) > -1

        if (prop === 'createTime' || prop === 'updateTime' || isConvertedProp) {
          isSystem = 1;
        } else {
          isSystem = sortedField.isSystem;
        }

        if (isConvertedProp) {
          prop = UserNameConvertMap[prop]
        }

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          column: prop,
        };

        if (
          prop === 'createTime'
          || prop === 'updateTime'
          || sortedField.formType === 'date'
          || sortedField.formType === 'datetime'
        ) {
          sortModel.type = 'date';
        } else if (prop === 'level' || prop === 'taskNo') {
          sortModel.type = 'string';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.sortModel = sortModel;
        this.fetchData();
      } catch (e) {
        console.error('e', e);
      }
    },
    /**
     *
     * @description 打开客户详情
     * @param {object} clientInfo 客户详情
     */
    openClientTab(clientInfo) {
      const {
        linkAuth,
        customerEntity
      } = clientInfo;
      const {
        id
      } = customerEntity;
      if (!linkAuth) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    openEventTab(clientInfo){
      let id = clientInfo.eventId;
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: id
      })
    },  
    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(taskId, taskNo) {
      if (!taskId) return;
      
      if (!this.globalIsHaveTaskViewDetailAuth) return

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'canViewTask=1',
        fromId
      })
    },
    jump(pN) {
      this.searchModel.pageNum = pN;
      this.fetchData();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.fetchData();
    },
    fetchData() {
      const {pageNum, pageSize, } = this.searchModel;
      const params = {
        ...this.buildSearchParams(),
        page: pageNum,
        pageSize,
      };

      // 排序
      if(this.sortModel){
        const { column, isSystem, sequence } = this.sortModel;
        params.sorts = [{
          property: isSystem ? column : `attribute.${column}`,
          direction: sequence,
        }, ];
      } 

      this.loading = true;

      TaskApi.search(params).then(res => {
          const list = res?.result?.content || []
          const total = res?.result?.totalElements || 0

          this.taskList = list
            .map(task => {
              task.createTime = formatDate(safeNewDate(task.createTime), 'YYYY-MM-DD HH:mm:ss');
              task.completeTime = task.completeTime && formatDate(safeNewDate(task.completeTime), 'YYYY-MM-DD HH:mm:ss');
              task.acceptUsedTime = this.timestamp(task.acceptUsedTime);
              task.taskUsedTime = this.timestamp(task.taskUsedTime);
              task.workUsedTime = this.timestamp(task.workUsedTime);
              task.taskResponseTime = this.timestamp(task.taskResponseTime);
              task.createToCompleteUsedTime = this.timestamp(task.createToCompleteUsedTime);
              if (task.planTime && this.planTimeType === 'date') {
                task.planTime = formatDate(safeNewDate(task.planTime), 'YYYY-MM-DD');
              }
              if (task.planStartTime && this.planStartTimeType === 'date') {
                task.planStartTime = formatDate(safeNewDate(task.planStartTime), 'YYYY-MM-DD');
              }
              if (task.planEndTime && this.planEndTimeType === 'date') {
                task.planEndTime = formatDate(safeNewDate(task.planEndTime), 'YYYY-MM-DD');
              }
              task.suggestion = atTextToHtml1(task.suggestion)
              return task;
            });
          this.searchModel.totalItems = total;
          this.loading = false;
        })
        .catch(e => console.error('fetch task caught e', e))
    },
    /**
     * @des 获取系统内的灰度
     */
    getSystemGrayInfo(){
      getAllGrayInfo().then(res=>{
        this.allGrayInfo = res;
      })
    },
    getTaskListInitData() {
      return getAsyncTaskListInitData().then(result => {
        return result?.data?.initJson || {}
      })
    },
    async getExpensePartField(){
      const _res = await TaskApi.getExpensePartField()
      if (_res.code == 0 && _res.result?.length) {
        _res.result.forEach(item=>{
          this.partField += `${item.fieldName},`
        })
      }
    },
    /**
     * @description 初始化
     */
    initialize() {
      // 默认回到第一页 批量编辑保持当前页面
      this.loading = true;
      return Promise.all([this.fetchTaskFields(), this.fetchTaskReceiptFields(), this.getCommonFields(), this.getTaskListInitData()])
        .then(async (res) => {
           // 解析基础组件 物流组件字段
          this.$set(this, 'taskFields', smoothLogisticsField(res[0] || []));
          // 解析自定义字段 物流组件字段
          this.$set(this, 'taskReceiptFields', smoothLogisticsField(res[1] || []));
           // 解析公共字段 物流组件字段
          this.$set(this, 'taskCommonFields', smoothLogisticsField(res[2] || []))
          this.initData = res[3] || {}
          let arr1 = res[0].find((item) => {
            return item.fieldName === 'planTime';
          });
          let arr2 = res[0].find((item) => {
            return item.fieldName === 'planStartTime';
          })
          let arr3 = res[0].find((item) => {
            return item.fieldName === 'planEndTime';
          });
          this.planTimeType = arr1?.setting.dateType || '';
          this.planStartTimeType = arr2?.setting.dateType || '';
          this.planEndTimeType = arr3?.setting.dateType || '';
          const qualityFields = await this.getQualityField()
          // 过滤重复字段
          this.taskFields = [...this.taskFields, ...qualityFields]
          this.buildColumns();
          this._exportColumns();
          this.fetchData()
        })
        .catch((err) => {
          this.loading = false;
          console.warn(err);
        });
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: '',
        tableName: 'task',
        isFromSetting: false
      };
      return TaskApi.getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    // 单独获取质保字段的相关信息
    getQualityField(){
      return TaskApi.getQualityFieldApi()
        .then(result => result?.data || [])
        .catch(() => [])
    },
    /**
     * @description 获取工单回执字段列表
     * @return {Promise}
     */
    fetchTaskReceiptFields() {
      let params = {
        typeId: '',
        tableName: 'task_receipt',
        isFromSetting: false
      };
      return TaskApi.getAllFields(params).then((result) => {
        result && result.forEach((field) => {
          field.group = 'task_receipt';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    /** 
     * @description 获取公共字段
    */
    getCommonFields(){
      let params = {
        tableName: 'all',
        typeId: '',
      };
      return TaskApi.getCommonFields(params).then((result) => {
        result && result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },

    /**
     * @description 过滤工单列表字段
     * @return {Array<TaskField>} 过滤后工单列表字段
     */
    filterTaskListFields() {
      let fields = this.taskListFields || [];
      let field = null;

      let newFields = [];

      for (let i = 0; i < fields.length; i++) {
        field = fields[i];

        // 基础版过滤产品、支付方式、结算时间、关联事件、曾打印字段
        if (
          this.isBasicEditionHideProduct
          && field.fieldName === 'product'
        ) {
          continue;
        }
        if (
          this.isBasicEditionHidePay
          && (field.fieldName === 'paymentMethod' || field.fieldName === 'balanceTime')
        ) {
          continue;
        }
        if (
          this.isBasicEditionHideEvent
          && field.fieldName === 'eventNo'
        ) {
          continue;
        }
        if (
          this.isBasicEditionHidePrintTask
          && field.fieldName === 'oncePrinted'
        ) {
          continue;
        }

        newFields.push(field);
      }

      return newFields;
    },
    /**
     * @description 构建列
     */
    async buildColumns() {
      const {
        paymentConfig
      } = this.initData;

      // 获取缓存在本地的选择列配置
      const localStorageData = await this.getLocalStorageData();
      const columnStatus = localStorageData.columnStatus || [];
      const localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});
      
      // 默认展示字段
      const defaultColumns = [{
        label: t('customer.detail.customerTaskTable.table.label.taskNo'),
        displayName: t('customer.detail.customerTaskTable.table.label.taskNo'),
        field: 'taskNo',
        fieldName: 'taskNo',
        show: true,
        isSystem: 1,
      }, {
        label: t('customer.detail.customerTaskTable.table.label.templateId'),
        displayName: t('customer.detail.customerTaskTable.table.label.templateId'),
        field: 'templateName',
        fieldName: 'templateName',
        show: true,
        width:'120px',
        sortable: 'custom',
        isSystem: 1,
      }, {
        label: t('customer.detail.customerTaskTable.table.label.productName'),
        displayName: t('customer.detail.customerTaskTable.table.label.productName'),
        field: 'product',
        fieldName: 'product',
        show: true,
        isSystem: 1,
      }, {
        label: t('customer.detail.customerTaskTable.table.label.state'),
        displayName: t('customer.detail.customerTaskTable.table.label.state'),
        field: 'state',
        fieldName: 'state',
        show: true,
        width:'120px',
        sortable: 'custom',
        isSystem: 1,
      }, {
        label: t('customer.detail.customerTaskTable.table.label.executor'),
        displayName: t('customer.detail.customerTaskTable.table.label.executor'),
        field: 'executorName',
        fieldName: 'executorName',
        show: true,
        width:'95px',
        sortable: 'custom',
        isSystem: 1,
      }, {
        label: t('customer.detail.customerTaskTable.table.label.createTime'),
        displayName: t('customer.detail.customerTaskTable.table.label.createTime'),
        field: 'createTime',
        fieldName: 'createTime',
        show: true,
        width:'120px',
        sortable: 'custom',
        isSystem: 1,
      }, {
        label: t('customer.detail.customerTaskTable.table.label.completeTime'),
        displayName: t('customer.detail.customerTaskTable.table.label.completeTime'),
        field: 'completeTime',
        fieldName: 'completeTime',
        show: true,
        width:'120px',
        sortable: 'custom',
        isSystem: 1,
      }, {
        label: t('customer.detail.customerTaskTable.table.label.suggestion'),
        displayName: t('customer.detail.customerTaskTable.table.label.suggestion'),
        field: 'suggestion',
        fieldName: 'suggestion',
        show: true,
        width:'120px',
        sortable: 'custom',
        isSystem: 1,
      }]

      let taskListFields = this.filterTaskListFields();
      let fields = taskListFields.concat(this.taskTypeFilterFields);
      fields = fields.filter(f => !['taskNo', 'templateName', 'state', 'product', 'executorName', 'createTime', 'completeTime', 'suggestion'].includes(f.fieldName))

      // 如果没有服务商资质则去除列表和选择列的相关信息
      if(!this.isProviderManager){
        fields = fields
          .filter(item => item.formType !== 'serviceProviderQualification')
          .filter(item => item.formType !== 'engineerQualification')
      }
      if(fields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        fields = fields.filter(val => val.formType !== 'relationForm')
      }
      // 合并质保信息
      if(this.taskFields.filter(item=>item.formType==="quality").length){
        fields.forEach((item,index)=>{
          if(item.fieldName==='product'){
            fields.splice(index+1,0,qualityFields[0],qualityFields[1],qualityFields[2])
          }
        })
      }

      // 里程字段合并
      let Mileage = this.taskFields.filter(item=>['taskEstimatedMileage','estimatedMileage','actualMileage'].includes(item.formType))
      if(Mileage.length){
        Mileage.forEach((item,index)=>{
          fields.push(item)
        })
      }

      fields = fields.concat(AbnormalList)
      
      // 故障库字段
      if(this.isFaultGrayscale) {
        fields = fields.concat(FaultLibrary)
      }

      fields = [...fields.filter(item=>!item.isCommon), ...this.commonFields].sort((a, b) => a.orderId - b.orderId).map(f => {
        // 除默认字段defaultColumns，其它字段默认都不显示，下面可以走缓存的show
        f.show = false
        return f
      });
      fields = [...defaultColumns, ...fields]

      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        fields = this.buildSortFields(fields, localColumns)
      }

      // E 高级搜索
      let columns = fields
        .filter(f => !['attachment', 'separator', 'info', 'autograph'].includes(f.formType))
        .map((field) => {
          let sortable = field.sortable;
          let minWidth = 120;

          if (['date', 'datetime', 'number', 'planStartTime', 'planEndTime'].indexOf(field.formType) >= 0) {
            sortable = 'custom';
            minWidth = 100;
          }

          if (['address'].indexOf(field.formType) >= 0) {
            minWidth = 200;
          }

          if (['level', 'updateTime', 'createUserName', 'executorName', 'state'].indexOf(field.fieldName) >= 0) {
            sortable = 'custom';
          }

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (sortable && field.displayName.length >= 4) {
            minWidth = 125;
          }

          if (
            field.formType === 'datetime'
            || field.fieldName === 'updateTime'
            || field.fieldName === 'createTime'
          ) {
            minWidth = 180;
          }

          if (
            ['taddress', 'templateName'].indexOf(field.fieldName) >= 0
          ) {
            minWidth = 200;
          }

          if (field.fieldName === 'customer') {
            sortable = 'custom';
            minWidth = 125;
          }
          if (field.fieldName === 'taskNo') {
            field.minWidth = 130
          }
          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
          };
        })
        .map((col) => {
          // 选择列配置 是否勾选（显示）&宽度
          let show = col.show === true;
          let width = col.width;
          let localField = localColumns[col.field]?.field || null;
          if (null != localField) {
            if (localField.width) {
              width =
                typeof localField.width == 'number'
                  ? `${localField.width}px`
                  : localField.width;
            }
            show = localField.show !== false;
          } 

          col.show = show;
          col.width = width;
          col.minWidth = col.width || 150;
          col.type = 'column';
          return col;
        });

      // 根据版本号判断是否需要支付方式
      if (!paymentConfig.version) {
        columns = columns.filter((item) => {
          return item.fieldName !== 'paymentMethod';
        });
      }

      this.columns = []
      this.$nextTick(() => {
        this.columns = columns;
      })
      return columns
    },
    // 选择列排序
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    },
    /**
     * @description 打开选择列设置
     */
    showAdvancedSetting() {
      this.$refs.advanced.open(this.columns, {});
    },
    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet('customer_task_list', '{}');
      return JSON.parse(dataStr);
    },
    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('customer_task_list', JSON.stringify(data));
    },
    // 保存选择列
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];
      this.$nextTick(() => {
        this.columns = columns.slice();
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.tip.saveSuccess'));
    },
    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = true;
      return exportAll && this.searchModel.totalItems > max
        ? t('common.base.tip.exportLimit', { max })
        : null;
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /**
     * @description 导出工单
     */
    async exportTask(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')} ${t('task.list.taskData')}.xlsx`;

      const ExportPanelComponent = this.$refs.exportPanel
      if (!ExportPanelComponent) {
        return console.warn('Caused: $refs.exportPanel is Empty')
      }

      let exportCheckedData = {
        checkedGroup: [],
        checkedMap: {},
        isCheckedAll: false,
        tooltip: true
      }
      console.log(exportCheckedData, '导出的数据')
      ExportPanelComponent.open(ids, fileName, false, exportCheckedData)
    },
    /** 导出列 */
    _exportColumns() {
      let {
        taskFields,
        taskReceiptFields
      } = this
      // 工单信息
      let taskSelfFields = [];
      // 回执信息
      let taskReceiptSystemFields = [
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'spare_name',
          field: 'spare_name',
          displayName: t('common.base.sparePart'),
          label: t('common.base.sparePart'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'apply_material',
          field: 'apply_material',
          displayName: t('common.form.type.materialVerifyEliminate'),
          label: t('common.form.type.materialVerifyEliminate'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'return_material',
          field: 'return_material',
          displayName: t('common.form.type.materialReturn'),
          label: t('common.form.type.materialReturn'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'service_name',
          field: 'service_name',
          displayName: t('common.form.type.serviceIterm'),
          label: t('common.form.type.serviceIterm'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
        {
          id: 5460,
          isSystem: 1,
          fieldName: 'balance_total',
          field: 'balance_total',
          displayName: t('task.list.displayName.feeInfo'),
          label: t('task.list.displayName.feeInfo'),
          formType: 'text',
          isNull: 1,
          isSearch: 0,
        },
      ];

      // 开启云仓灰度 则显示物料核销物料返还
      if(!this.isCloudwarehouse) {
        taskReceiptSystemFields = taskReceiptSystemFields.filter(item => item.fieldName !== 'apply_material' && item.fieldName !== 'return_material')
      }

      // 工单信息逻辑
      let linkman_list = '',
        address_list = '',
        product_list = ''
      taskSelfFields = taskFields.filter(field => filterExportFieldWithFormType(field))
      if (taskFields.length) {
        let first = taskFields.filter(item => {
          return item.fieldName === 'customer'
        })[0]
        if (first.setting.customerOption.linkman) {
          linkman_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmName',
            displayName: t('common.base.contact'),
            exportAlias: 'customerLinkman',
            formType: 'select',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            show: true,
            guideProfessions: [],
            isGuideData: false,
            guideData: false,
          },
          {
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmPhone',
            exportAlias: 'customerPhone',
            displayName: t('common.base.phone'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.address) {
          address_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'taddress',
            exportAlias: 'customerAddress',
            displayName: t('common.form.type.customerAddress'),
            formType: 'address',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.product) {
          product_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'product',
            exportAlias: 'product',
            displayName: t('common.base.product'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
      }
      taskSelfFields.forEach((item, index) => {
        if (item.fieldName === 'taskNo') {
          taskSelfFields.splice(index + 1, 0, {
            id: 476,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'templateName',
            exportAlias: 'templateName',
            displayName: t('common.task.taskType'),
            formType: 'text',
            defaultValue: null,
            isNull: 0,
            isSearch: 1,
            placeHolder: null,
            setting: {
              customerNameDuplicate: false,
            },
            orderId: 0,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          })
        }
        if (item.fieldName === 'customer') {
          if (linkman_list) {
            taskSelfFields.splice(index + 1, 0, linkman_list[0], linkman_list[1])
          }
          if (address_list) {
            taskSelfFields.splice(index + linkman_list.length + 1, 0, address_list[0])
          }
          if (product_list) {
            taskSelfFields.splice(index + linkman_list.length + address_list.length + 1, 0, product_list[0])
          }
        }
      })


      // 处理质保信息
      if(taskSelfFields.filter(item => item.fieldName === 'quality').length){
        taskSelfFields = taskSelfFields.filter(item => item.fieldName !== 'quality')
        taskSelfFields.forEach((item, index)=>{
          if(item.fieldName === 'product'){
            taskSelfFields.splice(index + 1, 0, qualityFields[0], qualityFields[1], qualityFields[2])
          }
        })
      }

      // 过滤 故障库 服务商字段
      taskSelfFields = taskSelfFields.filter(item => !['faultLibrary', 'serviceProviders'].includes(item.fieldName))

      // 公共字段放入工单信息
      // 工单类型-全部 导出不需要按orderid排序
      taskSelfFields = [...taskSelfFields.filter(item=>!item.isCommon), ...this.commonFields];
      
      taskSelfFields.map(item => {
        item.label = item.displayName
        item.export = true
        return item
      })

      if(taskSelfFields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        taskSelfFields = taskSelfFields.filter(item => item.formType !== 'relationForm')
      }


      // 回执信息逻辑
      const receiptFilterFields = ['sparepart', 'serviceIterm', 'materialReturn', 'materialVerifyEliminate']
      // 海伦哲特殊字段不允许被过滤
      const exportFieldBanFilterArr = this.isHandlerGray ? [FieldTypeMappingEnum.Attachment] : [];
      let taskReceiptFields_ = taskReceiptFields.filter(field => {
        return filterExportFieldWithFormType(field, exportFieldBanFilterArr) && !receiptFilterFields.includes(field.formType)
      })
      taskReceiptSystemFields = [
        ...taskReceiptSystemFields,
        ...taskReceiptFields_
      ].map((field) => {
        field.export = true;
        if(this.isHandlerGray && exportFieldBanFilterArr.includes(field.formType)){
          field['filterIsBan'] = true
        }

        // 解析物流组件字段展示
        if(field.formType === 'logistics'){
          if(field.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsNo) > -1){
            field.label = t('common.base.logisticsNo')
          }
      
           if(field.fieldName.indexOf(LogisticsFieldNameMappingEnum.LogisticsCompany) > -1){
            field.label = t('common.base.logisticsCompany')
          }
        }
        return field;
      });

      if(taskReceiptSystemFields.some(item => item.formType === 'relationForm')){
        // 过滤掉关联表单的相关内容
        taskReceiptSystemFields = taskReceiptSystemFields.filter(item => item.formType !== 'relationForm')
      }

      // 系统信息
      let sysList = [...allExport, ...AbnormalList]
      
      // 故障库字段
      if(this.isFaultGrayscale) {
        sysList = [...sysList,  ...FaultLibrary]
      }

      // 基础版过滤产品、支付方式、结算时间、结算人、关联事件、曾打印字段
      if (this.isBasicEditionHideProduct) {
        taskSelfFields = taskSelfFields.filter(item => item.fieldName !== 'product')
      }
      if (this.isBasicEditionHidePay) {
        sysList = sysList.filter(item => item.fieldName !== 'balanceTime' && item.fieldName !== 'paymentMethod' && item.exportAlias !== 'balanceUser')
      }
      if (this.isBasicEditionHideEvent) {
        sysList = sysList.filter(item => item.fieldName !== 'eventNo')
      }
      if (this.isBasicEditionHidePrintTask) {
        sysList = sysList.filter(item => item.exportAlias !== 'oncePrinted')
      }
      // 基础版导出列的系回执信息过滤备件、服务项目、费用信息字段
      const filterEnum = {
        'spare_name':()=>{
          return !this.isBasicEditionHidePart
        },
        'service_name':()=>{
          return !this.isBasicEditionHideServe
        },
        'balance_total':()=>{
          return !this.isBasicEditionHidePay
        }
      }
      taskReceiptSystemFields = taskReceiptSystemFields.filter(field => {
        try{
          if(!Reflect.has(filterEnum, field.fieldName)) return true
          return filterEnum[field.fieldName];
        }catch(err){
          console.warn('taskReceiptSystemFields.filter try catch err')
          return true
        }
      })

      this.exportColumns = [
        {
          label: t('task.taskInfo'),
          value: 'taskChecked',
          columns: taskSelfFields,
        },
        {
          label: t('task.receiptInfo'),
          value: 'receiptChecked',
          columns: taskReceiptSystemFields,
        },
        {
          label: t('task.systemInfo'),
          value: 'systemChecked',
          columns: sysList.map(item => {
            item.export = true
            item.label = item.displayName
            return item
          }),
        },
      ];
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const {
        receiptChecked,
        systemChecked,
        taskChecked,
      } = checkedMap
      const rootWindow = getRootWindow(window);
      const {
        loginUser
      } = this.initData;
      let exportAll = true;
      const searchParams = this.buildSearchParams();
      const all = {
        ...searchParams,
        taskIds: null,
        tagIds: loginUser.tagIds,
        dataLevel: loginUser.authorities.TASK_VIEW,
        tenantId: JSON.parse(rootWindow._init).user?.tenantId,
      };

      let exportSearchModel = {
        typeId: '',
      };
      let params = {
        exportSearchModel: JSON.stringify({
          ...all,
          ...{
            exportTotal: this.searchModel.totalItems,
          },
        }),
      };
      /** ********************* *********************/
      // 工单信息
      let export_task = this.exportData(0, taskChecked)
      // 回执信息
      let export_receipt_task = this.exportData(1, receiptChecked)
      // 系统信息
      let export_sys_task = this.exportData(2, systemChecked)

      // 关联表单
      if(this.taskFields.some(item => item.formType === 'relationForm')){
          const fieldNameList = this.taskFields.filter(item => item.formType === 'relationForm').map(item => item.fieldName);
          fieldNameList.forEach(item => {
            export_task = export_task.filter(val => val !== item)
          })
      }

      params['exportOneRow'] = exportOneRow
      params['data'] = exportAll ? '' : this.selectedIds.join(',');
      params['typeId'] = exportSearchModel.typeId;
      params['receiptChecked'] = export_receipt_task
        .map((item) => {
          if (item === 'spare_name') {
            // 添加定制客户的自定义导出备件字段
            item = `spare_name,spare_serialNumber,${this.partField}spare_type,spare_standard,spare_number,spare_cost`
          }
          if (item === 'service_name') {
            item = 'service_name,service_type,service_number,service_cost'
          }
          if (item === 'apply_material') {
            // 物料核销
            item = 'apply_material_name,apply_material_serialNumber,apply_material_property,apply_material_unit,apply_material_sn_manage,apply_material_sale_price,apply_material_out_ware_house,apply_material_out_ware_house_id,apply_material_pre_num,apply_material_sn,apply_material_warranty_status'
          }
          if (item === 'return_material') {
            // 物料返还
            item = 'return_material_name,return_material_serialNumber,return_material_property,return_material_unit,return_material_sn_manage,return_material_out_ware_house,return_material_out_ware_house_id,return_material_num,return_material_sn,return_material_way,return_material_company,return_material_code'
          }
          if (item === 'balance_total') {
            // 如果开启结算规则灰度
            if (this.isSettlementRuleGray) {
              item = ''
              params.taskSettlement =  ['ruleName', 'isFreeName', 'materialTotal', 'sparePartTotal', 'serviceTotal', 'disExpense', 'totalExpense', 'finalTotalAmount']
            } else {
              item = 'balance_total,balance_discount,balance_sum'
            }
          }
          return item;
        })
        .filter(Boolean)
        .join(',');
      params['sysChecked'] = export_sys_task
        .map((item) => {
          return item;
        })
        .join(',');
      params['checked'] = export_task
        .map((item) => {
          if (item === 'product') {
            item = 'product,productSN'
          }
          return item;
        })
        .join(',');
      return params;
    },
    buildSearchParams() {
      return {
        page: 1,
        pageSize: 10,
        dataLevel: 3,
        keyword: '',
        templateId: '',
        stateList: [],
        isException: null,
        exceptionStates: [],
        exceptionNodes: [],
        conditions: [],
        systemConditions: [
          {
            property: 'customerId',
            operator: 'eq',
            value: this.customerId
          }
        ],
        createUser: '',
        executor: '',
        synergyId: '',
        whoseInfo: 'my',
        balanceConditions: [],
      }
    },
    /**
     * 导出数据
     */
    exportData(number, list = []) {
      const export_list = this.exportColumns;
      let cardField = export_list[number].columns
      return cardField.map(v => {
        let bool = list.some(item => {
          if (v.exportAlias) {
            return v.exportAlias === item
          } 
          return v.fieldName === item
          
        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
    },
    // 跳转工单列表
    jumpTaskList() {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskList,
        params: `customerId=${this.customerId}&customerName=${this.customerName}`,
        reload: true,
      });
    },
    // 获取异常节点多语言label
    getTaskExceptionStateLabel(name) {
      return TaskExceptionStateLabelEnum[name] || name
    },
    // 获取创建方式的多语言label
    getSourceLabel(key) {
      return TaskCreateMethodLabelEnum[key] || key
    },
    /** 工单列表拨打电话 */
    async makePhoneCall(phone, isLinkman) {
      try {
        ctiCallOut(phone) // taskType:'customer'
      } catch (error) {
        console.error(error);
      }
    },
    /**
     * @description 显示最后一次更新记录
     * @param {Object} row 行数据
     */
    showLatestUpdateRecord(row) {
      if (row.latesetUpdateRecord) return;

      TaskApi.getTaskUpdateRecord({
        taskId: row.id
      })
        .then((res) => {
          if (!res || res.status) return;

          this.taskList.forEach((c) => {
            if (c.id === row.id) {
              this.$set(c, 'latesetUpdateRecord', res.data);
            }
          });
        })
        .catch((e) => console.error('e', e));
    },
    /**
     * @description 打开用户详情tab
     * @param {String} userId 用户id
     */
    openUserTab(userId) {
      if (!userId) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: userId,
        params: `noHistory=1&from=task`,
        fromId
      })
    },
    /** @return 人员userId和展示字段 */
    presonDisplayObj(attr, fieldName, row) {
      let obj = {};
      switch(fieldName) {
      case 'createUserName':
        obj = row.createUser;
        break;
      case 'executorName':
        obj = row.executorUser;
        break;
      case 'allotName':
        obj = row.allotUser;
        break;
      default:
        break;
      }
      
      obj = obj || {};
      
      return obj[attr];
    },
    // 处理人员显示
    getUserName (value) {
      // 多选
      if (Array.isArray(value)) {
        return value.map((i) => i.displayName || i.name).join(',');
      }

      let user = value || {};
      return user.displayName || user.name;
    },
    getUserIds (value) {
      // 多选
      if (Array.isArray(value)) {
        return value.map((i) => i.staffId);
      }

      let user = value || {};
      return [user.staffId];
    },
    getRelationUserIds (value) {
      // 客户产品关联跟人有关的字段 返回的是字符串
      if(!value) return []
      return value.split(',') || [];
    },
    /**
     * @description 派单方式文案
     */
    allotTypeText(params) {
      let text;
      switch (params) {
      case 1:
        text = t('task.detail.components.manualDispatch');
        break;
      case 2:
        text = t('task.detail.components.poolDispatch');
        break;
      case 3:
        text = t('task.detail.components.autoDispatch');
        break;
      default:
        text = '';
        break;
      }
      return text;
    },
    /**
     * @description 格式化服务团队
     */
    formatExecutorTags(executorTags) {
      if (null == executorTags) return '';
      
      return executorTags.map(item => item.name).join('、');
    },
    // 获取富文本内容
    openRichtextVisible(row, column){
      const richtextId = row.attribute[column.field] || ''
      if(!richtextId) return
      getRichTextContent({
        ids: [richtextId],
      })
        .then(res => {
          if (res.code == 0 || res.status == 0) {
            const richtextCon = res.result[0].content ?? '';
            this.richtextContent = richtextCon;
            this.richtextVisible = true;
          } else {
            throw res;
          }
        })
        .catch(err => {
          this.$notify.error({
            title: t('task.tip.errorTip'),
            message: err.message,
            duration: 2000,
          });
        })
    },
    /**
     * @description 格式化自定义地址
     * @param {Object} row 列表行数据
     * @param {Object} column 字段数据
     * @return {String} 过滤后的地址
     */
    formatCustomizeAddress(row, column) {
      const customizeAddress = column.isSystem ? row[column.formType] : row?.attribute[column.fieldName]
      if (null == customizeAddress) return '';

      return formatAddress(customizeAddress)
    },
    /**
     * @description 构建多行文本
     * @return {String}
     */
    buildTextarea(value) {
      return value
        ? value.replace(LINK_REG, (match) => {
          return `<a href="javascript:;" target="_blank" url="${match}">${match}</a>`;
        })
        : '';
    },
    /**
     * @description 打开外部链接
     * @param {Object} e 事件对象
     */
    openOutsideLink(e) {
      let url = e.target.getAttribute('url');
      if (!url) return;
      if (!/http/gi.test(url))
        return this.$platform.alert(t('common.base.tip.outsideLinkTip'));

      this.$platform.openLink(url);
    },
    /** 获取用户开启的配置节点 以及工单搜索范围 和 异常原因字段值 */
    async getTurnOnTaskExceptionNodeInfo() {
      const {success, result} = await TaskApi.getTurnOnTaskExceptionNodeInfo()
      if(success) {
        result.taskCustomExceptionNodeList.map(item => {
          item.exceptionName = this.getTaskExceptionStateLabel(item.exceptionName)
          return item
        })
        this.abnormalData = result
        this.abnormalData['hoverText'] = result.taskCustomExceptionNodeList.map(item => {return item.exceptionName}).join(',')
      }
    },
    abnormalLabel(type) {
      if (!this.abnormalData.taskCustomExceptionNodeList?.length) return
      const list = this.abnormalData.taskCustomExceptionNodeList.map(item => {return item.exceptionName})
      if (list.indexOf(type) !== -1) return true
      return false
    },
    getFanWei(type){
      for(let i of this.abnormalData.taskExceptionRange){
        if(i.switch){
          if(type === i.chineseName ){
            return true
          }
        }
      }
      return false
    },
    abnormalHover(item) {
      if (!item) return
      const {overTime, isPaused, oncePaused, onceOverTime, state, onceRefused, onceReallot, onceRollback, positionException, currIsReallot, currIsRoback} = item
      const s = safeNewDate().getTime()
      const e = safeNewDate(overTime).getTime()

      let value = []
      // 超时
      if(overTime && this.abnormalLabel(t('common.task.exceptionStatus.overTime')) && s > e && this.getFanWei(this.taskStateEnum.getState(item.state))) {
        value.push(t('common.task.exceptionStatus.overTime'))
      }
      if (isPaused && this.abnormalLabel(t('common.task.exceptionStatus.pause'))) {
        value.push(t('common.task.exceptionStatus.pause'))
      }
      if (oncePaused && this.abnormalLabel(t('common.task.exceptionStatus.oncePaused'))) {
        value.push(t('common.task.exceptionStatus.oncePaused'))
      }
      if (onceOverTime && this.abnormalLabel(t('common.task.exceptionStatus.onceOverTime'))) {
        value.push(t('common.task.exceptionStatus.onceOverTime'))
      }
      if (state === 'refused' && this.abnormalLabel(t('common.task.exceptionStatus.refused'))) {
        value.push(t('common.task.exceptionStatus.refused'))
      }
      if (onceRefused && this.abnormalLabel(t('common.task.exceptionStatus.onceRefused'))) {
        value.push(t('common.task.exceptionStatus.onceRefused'))
      }
      if (currIsReallot && this.abnormalLabel(t('common.task.exceptionStatus.allot'))) {
        value.push(t('common.task.exceptionStatus.allot'))
      }
      if (currIsRoback && this.abnormalLabel(t('common.task.exceptionStatus.rollback'))) {
        value.push(t('common.task.exceptionStatus.rollback'))
      }
      if (onceReallot && this.abnormalLabel(t('common.task.exceptionStatus.onceAllot'))) {
        value.push(t('common.task.exceptionStatus.onceAllot'))
      }
      if (onceRollback && this.abnormalLabel(t('common.task.exceptionStatus.onceRollback'))) {
        value.push(t('common.task.exceptionStatus.onceRollback'))
      }
      if (state === 'offed' && this.abnormalLabel(t('common.task.exceptionStatus.offed'))) {
        value.push(t('common.task.exceptionStatus.offed'))
      }
      if (positionException && this.abnormalLabel(t('common.task.exceptionStatus.positionException'))) {
        value.push(t('common.task.exceptionStatus.positionException'))
      }

      return value
    },
    /**
     * @description 时间戳转换
     */
    timestamp(value) {
      if (typeof value === 'number') {
        let h = value / 3600 < 0 ? 0 : parseInt(value / 3600), m;
        if (h > 0) {
          m = (value % 3600) ? Math.ceil((value % 3600) / 60) : value % 3600
        } else {
          m = Math.ceil(value / 60)
        }

        if(m > 59) {
          m = 0;
          h ++;
        }
        return t('task.list.howManyHourAndMinute', {h, m});
      } 
      return ''
    },
  },
  components:{
    [ArchiveDialog.name]:ArchiveDialog
  }
}